<template>
  <div class="app-container">
    <div>
      <!-- 条件栏 -->
      <NewPageFilter
        v-model:query="filterInfo.query.queryMap"
        :query-more-json="true"
        :filter-list="filterInfo.searchList"
        :filter-btn="filterInfo.searchBtn"
        :clear-type="clearType"
        :slip-select-request="slipSelectRequest"
      >
      </NewPageFilter>
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btnList">
          <template v-slot:filter-uploadFile>
            <el-upload
              :headers="uploadInfo.headers"
              :show-file-list="false"
              :on-success="uploadSuccess"
              :on-error="uploadError"
              :before-upload="beforeUpload"
              :action="uploadInfo.action"
            >
              <el-button>导入模板</el-button>
            </el-upload>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :checkBox="false"
        :row-class-name="tableRowClassName"
        @pageInfo="pageInfo"
      >
        <template v-slot:col-supplierName="scope">
          <span
            v-if="$permission('supplier:list')"
            class="slip-edit"
            @click="showDetail(scope.row)"
            >{{ scope.row.supplierName }}</span
          >
          <span v-else>{{ scope.row.supplierName }}</span>
        </template>
      </table-container>
    </div>
    <selectProduct
      v-if="productInfo.visible"
      @callback="_selectProduct"
      v-model:showDialog="productInfo.visible"
      :type="productInfo.type"
      :row="productInfo.row"
      :query="productInfo.query"
    />
    <SetPreference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    >
    </SetPreference>
    <AdvancedSearch
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      v-model:form-data="advancedSearchInfo.data"
      :field-list="tableInfo.fieldList"
      @callback="advancedSearchCallback"
    />
    <PageDialog
      v-if="dialogTipsInfo.visible"
      :title="dialogTipsInfo.title"
      v-model:visible="dialogTipsInfo.visible"
      :width="dialogTipsInfo.width"
      :bt-loading="dialogTipsInfo.btLoading"
      :bt-list="dialogTipsInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogTipsInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogTipsInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </PageDialog>
  </div>
</template>

<script setup name="bandQuantityProductManager">
import {
  purchBandQuantityCustomizeListPage,
  exportBandQuantity,
  deleteBandQuantity
} from "@/api/purch.js";
import { getCustomizeSetting, updateUserCustomize } from "@/api/customize";
import selectProduct from "./selectProduct";
import { exportTemplateExcel } from "@/api/pub";
// import defaultSetPreference from "@/components/SetPreference/defaultSetPreference";
import { ElLoading } from "element-plus";
const { proxy } = getCurrentInstance();
const uploadInfo = ref({
  action:
    import.meta.env.VITE_APP_BASE_API + "/purch/bandQuantity/import/excel",
  headers: {
    Authorization: proxy.$store.state.user.token,
  },
  loading: {},
});
const preferenceInfo = ref({
  visible: false,
});
const advancedSearchInfo = ref({
  visible: false,
  data: {},
});
//选择产品相关
const productInfo = ref({
  visible: false,
  type: 'add',
  row:'',
  query: {
    bandQuantityProduct: "0",
  },
});
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
});
const slipSelectRequest = ref(true);
const clearType = ref(true);
const dialogTipsInfo = ref({
  visible: false,
  title: "提示",
  btLoading: false,
  type: "",
  msg: "",
  width: "400px",
  flag: true,
  btList: [
    { label: "关闭", event: handleClose, show: true },
    {
      label: "打印",
      type: "primary",
      event: checkConfirm,
      show: true,
    },
  ],
});
// 过滤相关配置
const filterInfo = ref({
  query: {
    sortString: "",
    customizeUserVO: {},
    queryMap: {},
    queryParams: {
      sort: "create_time desc",
    },
  },
  searchList: [],
  searchBtn: [
    { type: "button", label: "搜索", event: search },
    { type: "button", label: "高级查询", event: advancedSearchShow },
    { type: "button", label: "重置", event: clearSearch },
  ],
  btnList: [
    {
      type: "button",
      label: "新增",
      show: proxy.$permission("bandQuantityProductManager:add"),
      event: add,
    },
    {
      type: "button",
      label: "下载模板",
      event: downloadTemplate,
      show: proxy.$permission("bandQuantityProductManager:downloadTemplate"),
    },
    { type: "slot", value: "uploadFile",show: proxy.$permission("bandQuantityProductManager:upload"), },
    {
      type: "button",
      label: "导出",
      event: exportExcel,
      show: proxy.$permission("bandQuantityProductManager:excelList"),
    },
    {
      type: "input",
      label: "名称/编码",
      value: "keyword",
      event: search,
    },
  ],
});
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  fieldList: [],
  handle: {
    fixed: "right",
    label: "操作",
    width: "140",
    btList: [
      {
        label: "修改",
        event: handleUpdate,
        show: proxy.$permission("bandQuantityProductManager:update"),
      },
      {
        label: "删除",
        event: handleDelete,
        show: proxy.$permission("bandQuantityProductManager:del"),
      },
    ],
  },
});

let obj = ref({
  commonName: {
      label: '通用名称',
      value: 'commonName',
      componentType: 'input',
      show: false,
      hidden: true,
    },
});
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
});
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj.value),
});
onMounted(() => {
  getCustomize();
});
function _selectProduct(rows) {
  getList()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      "bandQuantityProductList-com.slip.spd.entity.vo.purch.BandQuantityProductVO",
  };
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      proxy.$nextTick(() => {
        let data = res.data;
        filterInfo.value.query.customizeUserVO = data;
        tableInfo.value.fieldList = proxy.$fn.setFieldList(
          tableInfo.value.fieldList,
          data.detail
        );
        let searchInfo = proxy.$fn.setSearchList(
          filterInfo.value.searchList,
          data.detail
        );
        filterInfo.value.query.queryMap = {
          ...searchInfo.queryMap,
        };

        filterInfo.value.searchList = searchInfo.searchList;
        filterInfo.value.searchList.forEach((item) => {
          item.event = search;
        });
        filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
          filterInfo.value.query.queryMap
        );
        slipSelectRequest.value = _slipSelectRequest;
        tableInfo.value.api = purchBandQuantityCustomizeListPage;
        getList();
      });
    }
  });
}
function advancedSearchShow() {
  advancedSearchInfo.value.visible = true;
}
async function setPreferenceCallback(obj) {
  let vo = proxy.$fn.deepClone(obj.customizeUserVO);
  updateUserCustomize(vo).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value);
    }
  });
}

function advancedSearchCallback(obj) {
  filterInfo.value.query.queryMap = {};
  advancedSearchInfo.value.data = obj.data;
  proxy.$nextTick(() => {
    getList();
  });
  clearType.value = !clearType.value;
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  );
}
function clearSearch() {
  clearType.value = !clearType.value;
  advancedSearchInfo.value.data = {};
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  );
  search();
}

function search() {
  advancedSearchInfo.value.data = {};
  tableInfo.value.initCurpage = Math.random();
  tableInfo.value.refresh = Math.random();
}

// 获取列表
function getList() {
  tableInfo.value.refresh = Math.random();
}
// 添加
function add() {
  // productInfo.value.query.idNotIn = tableInfo.value.data
  //   .map(function (item) {
  //     return item.productId;
  //   })
  //   .toString();
    productInfo.value.type = 'add'
  productInfo.value.visible = true;
}
// 删除
function handleDelete(data) {
  let ids = [data.id];
  proxy
    .$confirm(`确认删除吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(() => {
      deleteBandQuantity(ids).then((resp) => {
        if (resp && resp.success) {
          tableInfo.value.initCurpage = Math.random();
          tableInfo.value.refresh = Math.random();
        }
      });
    });
}
//修改
function handleUpdate(row) {
  productInfo.value.type = 'update'
  productInfo.value.row = JSON.parse(JSON.stringify(row))
  productInfo.value.visible = true;
}
function showDetail(row) {}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem("storeRowId");
  if (rowId && row.id === Number(rowId)) {
    return "check-row";
  }
  return "";
}
//打印导出
function pageInfo(obj) {
  page.value = obj;
}
function exportExcel() {
  //导出
  dialogTipsInfo.value.visible = true;
  dialogTipsInfo.value.type = "excel";
  dialogTipsInfo.value.msg = "请选择数据导出范围";
  dialogTipsInfo.value.btList[1].label = "导出";
  dialogTipsInfo.value.flag = true;
}
function checkConfirm() {
  if (dialogTipsInfo.value.type === "excel") {
    exportExcelList();
  } else if (dialogTipsInfo.value.type === "print") {
    printList();
  }
  dialogTipsInfo.value.visible = false;
  dialogTipsInfo.value.msg = "";
}
function handleClose() {
  dialogTipsInfo.value.visible = false;
}
function exportExcelList() {
  let query = {
    customizeDto: filterInfo.value.query,
  }
  let params = {
    ...query,
    ...page.value,
    page: dialogTipsInfo.value.flag,
  };
  exportBandQuantity(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp);
    }
  });
}
function downloadTemplate() {
  exportTemplateExcel("band_quantity_product").then((res) => {
    if (res) {
      proxy.$fn.parseExcel(res);
    }
  });
}
function beforeUpload(file) {
  //发生请求时打开加载动画
  uploadInfo.value.loading = ElLoading.service({
    fullscreen: true,
    background: "rgba(255,255,255,.4)",
  });
  let fileType = ["xlsx"];
  let fileSize = proxy.$store.state.permission.systemConfig.max_file_size;
  let isFileType = fileType.some(
    (type) => file.name.split(".")[file.name.split(".").length - 1] === type
  );
  const isLt = file.size / 1024 / 1024 < fileSize;
  if (!isFileType) {
    proxy.$message.error({
      message: `文件格式不正确, 请上传 ${fileType.join(" / ")} 格式文件!`,
      showClose: true,
      duration: 3500,
    });
    uploadInfo.value.loading.close();
    return false;
  }
  if (!isLt) {
    proxy.$message.error({
      message: `上传文件大小不能超过 ${fileSize} MB!`,
      showClose: true,
      duration: 3500,
    });
    uploadInfo.value.loading.close();
    return false;
  }
  return isFileType && isLt;
}
function uploadSuccess(resp) {
  uploadInfo.value.loading.close();
  if (resp && resp.success) {
    proxy.$message.success({
      duration: 3000,
      showClose: true,
      message: resp.msg,
    });
    getList();
  } else {
    proxy.$message.error({
      message: resp.msg,
      duration: 3000,
      showClose: true,
    });
  }
}
function uploadError(err) {
  if (err) {
    proxy.$message.error({
      message: "系统错误",
      duration: 3000,
      showClose: true,
    });
  }
  uploadInfo.value.loading.close();
}
</script>

<style scoped></style>
